package v1

import (
	"RoccBlog/global"
	"RoccBlog/model"
	"RoccBlog/repository"
	"RoccBlog/util"
)

type CacheRepository struct {
	repository.BaseRepository
}

func (r *CacheRepository) Create(data model.Cache) error {
	return global.DB.Create(&data).Error
}

func (r *CacheRepository) Delete(id int) error {
	db := global.DB.Model(&model.Cache{})
	err := db.Association("CacheValues").Clear()
	if err != nil {
		db.Rollback()
		return err
	}
	err = db.Delete(model.Cache{}, id).Error
	if err != nil {
		db.Rollback()
		return err
	}

	db.Commit()
	return err
}

func (r *CacheRepository) Update(data model.Cache) error {
	return global.DB.Model(&data).Updates(&data).Error
}

func (r *CacheRepository) Select(pageNum, pageSize int) (any, error) {
	var (
		list  []model.Cache
		count int64
		err   error
	)
	db := global.DB.Model(&model.Cache{})

	err = db.Count(&count).Error
	if err != nil {
		return nil, err
	}

	err = db.Offset((pageNum - 1) * pageSize).Limit(pageSize).Find(&list).Error
	return util.ToPageInfo(count, pageSize, pageNum, list), err
}

func (r *CacheRepository) SelectById(id int) (model.Cache, error) {
	var cache model.Cache
	err := global.DB.Preload("CacheValue").Take(&cache, id).Error
	return cache, err
}

func (r *CacheRepository) DeleteCacheValue(id int) error {
	return global.DB.Delete(&model.CacheValue{}, id).Error
}

func (r *CacheRepository) CreateCacheValue(value model.CacheValue) error {
	return global.DB.Create(&value).Error
}
